import {
  vncConnection
} from "@/service/swagger/ResourceInitController.js";

console.log(111, vncConnection)
vncConnection({})

let jQuery = require('jquery')
// require('@/libs/popper/popper.min.js')
// require('@/libs/bootstrap/bootstrap.min.js')
require('@/libs/xterm/xterm.min.js')
require('@/libs/jquery/jquery.min.js')

// require('@/libs/fullscreen/fullscreen.min.js')


console.log(jQuery)

var wssh = {};


// jQuery(function($){
/*jslint browser:true */
// jQuery(function($){
var status = $('#status'),
  btn = $('.btn-primary'),
  style = {};


function parse_xterm_style() {
  var text = $('.xterm-helpers style').text();
  var arr = text.split('xterm-normal-char{width:');
  style.width = parseFloat(arr[1]);
  arr = text.split('div{height:');
  style.height = parseFloat(arr[1]);
}


function current_geometry() {
  if (!style.width || !style.height) {
    parse_xterm_style();
  }

  var cols = parseInt(window.innerWidth / style.width, 10) - 1;
  var rows = parseInt(window.innerHeight / style.height, 10);
  return {
    'cols': cols,
    'rows': rows
  };
}


function resize_term(term, sock) {
  var geometry = current_geometry(),
    cols = geometry.cols,
    rows = geometry.rows;
  // console.log([cols, rows]);
  // console.log(term.geometry);

  if (cols !== term.geometry[0] || rows !== term.geometry[1]) {
    console.log('resizing term');
    term.resize(cols, rows);
    sock.send(JSON.stringify({
      'resize': [cols, rows]
    }));
  }
}

function callback(msg) {
  console.log(msg)
  // if (msg.status) {
  //   status.text(msg.status);
  //   setTimeout(function () {
  //     btn.prop('disabled', false);
  //   }, 3000);
  //   return;
  // }

  // var ws_url = window.location.href.replace('http', 'ws'),
  // join = (ws_url[ws_url.length-1] === '/' ? '' : '/'),
  // url = ws_url + join + 'ws?id=' + msg.ws,

  var sock = new window.WebSocket(msg.ws),
    encoding = msg.encoding,
    terminal = document.getElementById('#terminal'),
    term = new window.Terminal({
      cursorBlink: true,
    });

  // console.log(url);
  console.log(encoding);
  wssh.sock = sock;
  wssh.term = term;

  term.on('data', function (data) {
    // console.log(data);
    sock.send(JSON.stringify({
      'data': data
    }));
  });

  sock.onopen = function () {
    $('.container').hide()
    term.open(terminal, true);
    term.toggleFullscreen(true);
  };

  sock.onmessage = function (msg) {
    var reader = new window.FileReader();
    reader.onloadend = function () {
      var decoder = new window.TextDecoder(encoding);
      var text = decoder.decode(reader.result);
      // console.log(text);
      term.write(text);
      if (!term.resized) {
        resize_term(term, sock);
        term.resized = true;
      }
    };

    reader.readAsArrayBuffer(msg.data);
  };

  //连接报错
  sock.onerror = function (e) {
    console.log(e, 11111111111111);
    $('.container').hide();
    term.open(terminal, true);
    term.toggleFullscreen(true);
  };
  //连接关闭
  sock.onclose = function (e) {
    window.close()
    // $('#connect').show()
    // term.open(terminal, true);
    // term.toggleFullscreen(true);
    console.log(e);
    term.destroy();
    wssh.term = undefined;
    wssh.sock = undefined;
    // $('.container').hide()
    status.text(e.reason);
    btn.prop('disabled', false);
  };
}

window.onload = function () {
  $('.nameipt').focus() //登录名聚焦
}

let str = window.location.search
console.log(str.indexOf('vncToken='))
var vncToken = str.substring(str.indexOf('vncToken=') + ("vncToken=").length)
// //输入名字后回车
$("body").on("keydown",'.nameipt',function(event){
  if (event.keyCode == 13 && $('.nameipt').val() != '') {
    //显示密码
    $('.passwordbox').show()
    //聚焦密码框
    $('.pasdipt').focus()
  }
})
// // //输错清空
// $('body').on("keydown",'pasdbox',function (event) {
//   if (event.keyCode == 67 && event.ctrlKey) {
//     $('.pasdbox').hide()
//     $('.pasdipt').val("")
//     $('.nameipt').val("")
//     $('.nameipt').focus()
//     $('#errorinfo').hide()
//     $('#errorinfo').html('')
//   }
// })
// auto聚焦
// $('html').on("click",'#connect',function () {
//   if ($('.pasdbox').css('display') == 'flex') {
//     $('.pasdipt').focus()
//   } else {
//     $('.nameipt').focus()
//   }
// })
//提交
$('body').on("keydown",'.pasdipt',function (event) {
  if (event.keyCode == 13) {
    var params = {
      password: $('.pasdipt').val(),
      username: $('.nameipt').val(),
      vncToken: vncToken,
    }
    $('.pasdipt').blur()
    $('.totipinfo').show()
    vncConnection(params).then(ret => {
      //提交成功
      $('.totipinfo').hide()
      if (ret.code == 0) {
        var msg = {
          status: null,
          encoding: 'utf-8',
          ws: ret.data
        }
        $('#connect').hide()
        $('.totipinfo').hide()
        callback(msg)
      } else {
        //失败
        $('.errorinfo').show()
        $('.errorinfo').html(ret.message)
        $('.pasdipt').removeClass('pasdipt')
        $('.nameipt').removeClass('nameipt')
        $('.passwordbox').removeClass('passwordbox')
        $('.totipinfo').removeClass('totipinfo')
        appendElement()
        $('.nameipt').focus() //登录名聚焦
      }
    })
  }
})

function appendElement(){
  var nameipt = `
            <div class="row">
              <div class="col" style="margin-top:-25px;">
                <code style="color:#fff;margin-left:15px">login:</code>
                <input type="text" style="background: #000;color: #fff;outline:none;border:none;" class="nameipt">
              </div>
            </div>
            `
  var pasdipt = `
            <div class="row passwordbox"  style="position:relative;top:-25px;">
              <div class="col">
                <code style="color:#fff;margin-left:15px">password:</code>
                <input autocomplete="new-password"  
                type="password" 
                style="background: #000;caret-color:#fff;color: #000;outline:none;border:none;" 
                class="pasdipt">
              </div>
            </div>
          `
  var messageinfo = `
          <div class="row">
            <div class="col" style="margin-left:15px;margin-top:-25px;">
              <p class="errorinfo" style="color:#fff;margin-top:-20px;display:none;"></p>
              <p class="totipinfo" style="color:#fff;margin-top:-20px;display:none;">正在连接中...</p>
            </div>
          </div>
        `
  $('#connect').append(nameipt,pasdipt,messageinfo)
}
$(window).resize(function () {
  if (wssh.term && wssh.sock) {
    resize_term(wssh.term, wssh.sock);
  }
})

// })
